package com.tanhua.admin.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.mapper.AnalisisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.vo.Analysis;
import org.apache.ibatis.annotations.Update;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {
    @Autowired
    private AnalisisMapper analisisMapper;
    @Autowired
    private LogMapper logMapper;
    /**
     * 计算日志表中的数据，保存或者更新到统计表中
     */
    public void analisis() throws Exception {
        String today  = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //用hutool工具包获取昨天的时间，查看次日留存
        String yesterDay = DateUtil.yesterday().toString();
        //新注册用户数
     Integer reNum = logMapper.queryByTimeAndType("0102",today);
        //1.2 活跃用户数
      Integer actNum = logMapper.queryByTime(today);
        //1.3 登陆次数
       Integer loNum = logMapper.queryByTimeAndType("0101", today);
        //1.4 次日留存用户数
       Integer retNum = logMapper.queryNumRetention1d(today, yesterDay);
        //2、根据统计日志查询数据
        LambdaQueryWrapper<Analysis> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Analysis::getRecordDate, today);
        Analysis analysis = analisisMapper.selectOne(wrapper);
        //3、判断数据是否存在
        if(analysis==null){
            //3.1 数据不存在，保存
            analysis = new Analysis();
            analysis.setNumActive(actNum);
            analysis.setNumLogin(loNum);
            analysis.setNumRegistered(reNum);
            analysis.setNumRetention1d(retNum);
            analysis.setCreated(new Date());
            //需要传入日期类型的参数，SimpleDateFormat把today格式化为date
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(today));
            analisisMapper.insert(analysis);
        }else {//3.2 数据存在，更新
            analysis.setNumRetention1d(retNum);
            analysis.setCreated(new Date());
            analysis.setNumLogin(loNum);
            analysis.setNumActive(actNum);
            analysis.setNumRegistered(reNum);
            analisisMapper.updateById(analysis);
        }


    }
}
